﻿using Furion.DatabaseAccessor;
using iWare.Wms.WorkerService.ThirdDB;
using Microsoft.EntityFrameworkCore;

namespace iWare.Wms.WorkerService
{
    public class PurchaseStatusERP : BackgroundService
    {
        private readonly ILogger<PurchaseStatusERP> _logger;
        // 服务工厂
        private readonly IServiceScopeFactory _scopeFactory;

        public PurchaseStatusERP(ILogger<PurchaseStatusERP> logger,
                      IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        // 启动
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }

        // 执行逻辑
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                //定时更新采购单状态
                await EditPurchaseStatus();

                await Task.Delay(10 * 60 * 1000, stoppingToken);
            }
        }

        #region 定时更新采购单状态
        /// <summary>
        /// 定时更新采购单状态
        /// </summary>
        /// <returns></returns>
        public async Task EditPurchaseStatus()
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var services = scope.ServiceProvider;
                var respository = Db.GetSqlRepository<ERPDbContextLocator>();

                //获取实体仓储
                var _purchaseOrderRep = Db.GetRepository<PurchaseOrder>(services);

                var purchaseOrder = await _purchaseOrderRep.DetachedEntities.Where(z => z.Status != PurchaseStatusEnum.Complete
                  && z.Status != PurchaseStatusEnum.Delete && z.IsJiaJiJian == YesOrNot.N).ToListAsync();

                foreach (var item in purchaseOrder)
                {
                    var purtcOutputList = await respository
                    .SqlQueryAsync<PURTCOutput>
                    (@"select  TC001,  --采购单别
                               TC002,  --采购单号
                               TC003,  --采购日期
                               TC004,  --供应商
                               TC009,  --备注
                               TC011,  --采购人员
                               TC023,  --数量合计
                               TC047,  --项目编号
                               UDF01,  --收货地址
                               TC030,  --签核状态码  0.待处理、S.传送中、1.签核中、2.退件、3.已核准、4.撤销审核中、5.作废中、6.取消作废中、N.不运行电子签核
                               TCD01   --是否结束 N:未结束、Y:结束 [DEF:""N""]
                       from PURTC where TC002='" + item.PurchaseNo + "' and TC001='" + item.PurchaseType + "' and TC047='" + item.ProjectCode + "'");

                    foreach (var itemDetail in purtcOutputList)
                    {
                        if (itemDetail.TCD01 == "Y")
                        {
                            item.Status = PurchaseStatusEnum.Complete;
                            await _purchaseOrderRep.UpdateAsync(item);
                        }
                    }
                }

                Console.WriteLine("定时更新采购单状态");
            }
        }
        #endregion

        // 停止
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }
    }
}
